<script setup lang="ts">
import { reqAddMessage } from '@/api/repair';
import { reqFindMessageAndComplain, reqFindMyMessage, reqRemoveMessage } from '@/api/supermarket';
import { useStore } from '@/pinna';
import { Refresh } from '@element-plus/icons-vue';
import { Search, CirclePlus } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Ref, computed, onMounted, ref, toValue, unref } from 'vue';
import { useRoute, useRouter } from "vue-router";

// 搜索栏
const formLabelWidth = '100px'
const pageNo: Ref<number> = ref(1)
const pageSize = ref(1000)
const router = useRouter();

const messageRef = ref({
    isMessage: true,
    message: ''
})
const searchMessageRef = ref({
    isMessage: '',
    isAllMessage: true,
    message: ''
})
const total = ref(0)
const tableData = ref([])
const infoStore = useStore()
onMounted(() => {
    findData()
})
const reset = () => {
    messageRef.value = {
        isMessage: true,
        message: ''
    }
    searchMessageRef.value = {
        isMessage: '',
        isAllMessage: true,
        message: ''
    }
    findData()
}

const handleSizeChange = (val: number) => {
    pageSize.value = val
    findData()
}

const handleCurrentChange = (val: number) => {
    pageNo.value = val
    findData()
}

const route = useRoute();
const isRouterUser = computed(() => {
    return route.path.includes('reception')
})

const findData = async () => {
    searchMessageRef.value.isAllMessage = isRouterUser.value || true
    const params =JSON.parse(JSON.stringify(unref(searchMessageRef.value))) 
    params.isMessage = params.isMessage == '1' ? true : (params.isMessage == '') ? '' : false
    if (searchMessageRef.value.isAllMessage) {
        await reqFindMessageAndComplain({
            pageNo: toValue(pageNo),
            pageSize: toValue(pageSize),
            ...params
        }).then((res: any) => {
            const { code, data, total: tableTotal } = res

            if (code === 200) {
                tableData.value = data
                total.value = tableTotal

            } else {
                ElMessage({
                    message: '请求异常',
                    type: 'warning'
                })
            }
        })
    } else {
        await reqFindMyMessage({
            pageNo: toValue(pageNo),
            pageSize: toValue(pageSize),
            ...unref(searchMessageRef)
        }).then((res: any) => {
            const { code, data, total: tableTotal, msg = '' } = res

            if (code === 200) {
                tableData.value = data
                total.value = tableTotal

            } else if (code == 550) {
                console.log('123');

                router.push('/login')
                localStorage.setItem('isLogin', 'false')
                ElMessage({
                    message: msg || '请求异常',
                    type: 'warning'
                })
            } else {
                ElMessage({
                    message: '请求异常',
                    type: 'warning'
                })
            }
        })
    }

}
const dialogHostTitle = ref('')
const dialogHost = ref(false)

const addMessageDialog = () => {
    messageRef.value = {
        isMessage: true,
        message: ''
    }
    dialogHostTitle.value = '留言板'
    dialogHost.value = true
}
const addMessageSubmit = async () => {
    console.log({ ...unref(messageRef) });

    await reqAddMessage({ ...unref(messageRef) }).then((res: any) => {
        const { code } = res

        if (code === 200) {
            ElMessage({
                message: messageRef.value.isMessage ? '留言成功' : '投诉成功',
                type: 'success'
            })
            dialogHost.value = false
            findData()

        } else {
            const message = res.msg || '请求异常'
            ElMessage({
                message: message,
                type: 'warning'
            })
        }
    })
}
const deleteHostDialog = async (id: string) => {
    ElMessageBox.confirm(
        '是否确认删除该留言?',
        '删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            await reqRemoveMessage({ id }).then((res: any) => {
                if (res.code === 200) {
                    ElMessage({
                        message: '删除成功',
                        type: 'success'
                    })
                    findData()
                } else {
                    ElMessage({
                        message: '请求异常',
                        type: 'warning'
                    })
                }
            })
        })

}
</script>
<template>
    <el-card>
        <template v-if="!isRouterUser" #header>
            <div class="card-header">
                <span><strong>{{ infoStore.$state.info.role == 'admin' ? '留言管理' : '留言查看' }}</strong></span>
            </div>
        </template>
        <div class="query-input">
            <el-select @change="findData()" :clearable="true" v-model="searchMessageRef.isMessage" placeholder="留言类型">
                <el-option label="留言" :value="'1'"></el-option>
                <el-option label="投诉" :value="'0'"></el-option>
            </el-select>
            <el-input style="margin-left:5px" v-model="searchMessageRef.message" placeholder="留言内容" />
            <el-button type="primary" @click="findData()">
                <el-icon>
                    <Search />
                </el-icon>
                查询
            </el-button>
            <el-button type="danger" @click="reset()">
                <el-icon>
                    <Refresh />
                </el-icon>
                重置
            </el-button>
            <el-button v-if="isRouterUser" key="'添加留言'" @click="addMessageDialog()" :icon="CirclePlus" type="primary"
                text bg class="addUser">添加留言</el-button>
        </div>
        <div class="card-layout" v-if="isRouterUser">
            <el-card class="layout-style" v-for="(row, index) in (tableData as any)"
                style="max-width: 480px;width: 32%;height: 340px;">
                <template #header>
                    <div class="card-header">
                        <span>{{ (index + 1) }}</span>
                    </div>
                </template>
                <div style="height:150px">
                    <p class="text item">{{ '留言类型: ' + (row?.isMessage == "true" ? '留言' : '投诉') }}</p>
                    <p class="text item">{{ '留言内容: ' + row?.message || '-' }}</p>
                </div>

                <template #footer>
                    <p style="color: blue;font-size: 12px;float: right;">{{ '创建时间: ' + (row?.createTime || '暂无')
                        }}</p>
                </template>
            </el-card>
        </div>
        <el-card v-else>
            <div>
                <el-button v-if="isRouterUser" key="'添加留言'" @click="addMessageDialog()" :icon="CirclePlus"
                    type="primary" text bg class="addUser">添加留言</el-button>
            </div>
            <el-table :data="tableData" stripe style="width: 100%">
                <el-table-column prop="isMessage" label="留言类型">
                    <template #default="scope">
                        <el-tag v-if="scope.row.isMessage == 'true'" type="success">留言</el-tag>
                        <el-tag v-else type="danger">投诉</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="message" label="留言内容">
                    <template #default="scope">
                        <div>{{ scope.row.message || '-' }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间">
                    <template #default="scope">
                        <div>{{ scope.row.createTime || '-' }}</div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                    <template #default="scope">
                        <el-space wrap>
                            <el-button type="primary" size="small" plain
                                @click="deleteHostDialog(scope.row.id)">删除</el-button>
                        </el-space>
                    </template>
                </el-table-column>
            </el-table>

            <div class="demo-pagination-block">
                <el-pagination v-model:current-page="pageNo" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 40]"
                    :background="false" :total="total" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </el-card>
    <el-dialog v-model="dialogHost" :title="dialogHostTitle">
        <el-form :model="messageRef">
            <div>
                <el-form-item label="留言类型:" :label-width="formLabelWidth" clearable required>
                    <el-select v-model="messageRef.isMessage" placeholder="Select" size="large" style="width: 240px">
                        <el-option key="1" label="留言" :value="true" />
                        <el-option key="2" label="投诉" :value="false" />
                    </el-select>
                </el-form-item>
                <el-form-item :label="messageRef.isMessage ? '留言信息' : '投诉信息'" :label-width="formLabelWidth" clearable
                    required>
                    <el-input v-model="messageRef.message" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
                        :placeholder="messageRef.isMessage ? '请输入留言信息' : '请输入投诉信息'" />
                </el-form-item>
            </div>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogHost = false">取消</el-button>
                <el-button type="primary" @click="addMessageSubmit()">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<style scoped lang="scss">
.el-input {
    margin-right: 5px;
    width: 400px;
}

.query-input {
    display: flex;
    gap: 10;
    margin-bottom: 45px
}

.el-card {
    margin-bottom: 10px;
}

.demo-pagination-block {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.addUser {
    float: right;
    margin-right: 10px;
}

.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

/* 
.el-input & .el-textarea  {
  width: 300px;
} */
.el-textarea {
    width: 400px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

.card-layout {
    cursor: pointer;
    display: flex;
    flex-wrap: wrap;
    flex-direction: row;
    align-items: flex-start;
    justify-content: space-around;
}

.layout-style:hover {
    box-shadow: 5px 5px 5px rgb(170, 166, 166);
}
</style>